package engine;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * Klasa służąca do wysyłania maili z konta pocztowego meetp.autoreply@gmail.com
 * @author Alien
 *
 */
public class Mailer {
	
	public static void main(String [] args){
		Mailer.sendMail("alien11689@gmail.com", "test", "xkjfjsidojfklsdjfds");
	}
	
	/**
	 * Metoda do wysyłania wiadomości z konta pocztowego meetp.autoreply@gmail.com
	 * @param to do kogo
	 * @param subject temat
	 * @param text treść wiadomośći
	 * @return true, gdy usało się wysłać; false, gdy operacja nie powiodła się
	 */
	public static boolean sendMail(String to,String subject, String text){
		Session session = Session.getDefaultInstance(mailProperties);
		MimeMessage message = new MimeMessage(session);
		try {
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
			message.setSubject(subject);
			message.setText(text);
			Transport transport = session.getTransport("smtp");
			transport.connect("smtp.gmail.com", 465, "meetp.autoreply@gmail.com", "eeteam2011");
			transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
			transport.close();
		} catch (AddressException e) {
			e.printStackTrace();
			return false;
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	private static Properties mailProperties = new Properties();
	static{
		//ustawienie parametrów wiadomości
		mailProperties.put("mail.transport.protocol", "smtp");
		mailProperties.put("mail.smtp.starttls.enable","true");
		mailProperties.put("mail.smtp.host", "smtp.gmail.com");
		mailProperties.put("mail.smtp.auth", "true");
		mailProperties.put("mail.smtp.user", "meetp.autoreply@gmail.com");
		mailProperties.put("mail.smtp.port", "465");
		mailProperties.put("mail.smtp.socketFactory.port", "465");
		mailProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		mailProperties.put("mail.smtp.socketFactory.fallback", "false");
	}
}
